package com.example.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class ZookeeperWatcherDemo {

    public static void main(String[] args) throws Exception {

        CuratorFramework framework = CuratorFrameworkFactory.builder()
                .connectString("192.168.232.130:2181,192.168.232.130:2182,192.168.232.130:2183")
                .sessionTimeoutMs(5000)// 会话超时时间
                .connectionTimeoutMs(5000)// 连接超时时间
                .namespace("gupao") // 隔离名称
                .retryPolicy(new ExponentialBackoffRetry(1000, 3)) // 重试策略
                .build();

        framework.start();

        addListenerWithNode(framework);
        addListenerWithChild(framework);
        System.in.read();

    }

    /**
     *  监控当前节点的  增删改 事件， 不能监控到子节点
     * @param framework
     * @throws Exception
     */
    private static void addListenerWithNode(CuratorFramework framework) throws Exception {

        NodeCache nodeCache = new NodeCache(framework, "/watch", false);
        NodeCacheListener nodeCacheListener = ()->{
            System.out.println("receive Node Changed");
            System.out.println(nodeCache.getCurrentData().getPath() + "  ---  " + nodeCache.getCurrentData().getData());
        };
        nodeCache.getListenable().addListener(nodeCacheListener);
        nodeCache.start();

    }

    /**
     *  监控子节点事件
     * @param framework
     * @throws Exception
     */
    private static void addListenerWithChild(CuratorFramework framework) throws Exception {

        PathChildrenCache nodeCache = new PathChildrenCache(framework, "/watch", true);
        PathChildrenCacheListener cacheListener = (curatorFramework, pathChildrenCacheEvent)->{

            System.out.println(pathChildrenCacheEvent.getType() + " --> "
                    + new String(pathChildrenCacheEvent.getData().getData()));
        };
        nodeCache.getListenable().addListener(cacheListener);
        nodeCache.start(PathChildrenCache.StartMode.NORMAL);

    }

}
